package com.quan.upms.rpc.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import tk.mybatis.mapper.entity.Condition;

import com.quan.base.common.base.service.support.BaseService;
import com.quan.base.common.exception.BizException;
import com.quan.upms.rpc.api.UpmsDepartmentService;
import com.quan.upms.rpc.dao.mapper.UpmsDepartmentMapper;
import com.quan.upms.rpc.dao.mapper.UpmsUserCompanyDeptAssignMapper;
import com.quan.upms.rpc.model.UpmsDepartment;
import com.quan.upms.rpc.model.UpmsUserCompanyDeptAssign;

@Service
public class UpmsDepartmentServiceImpl extends BaseService<UpmsDepartment, Integer> implements UpmsDepartmentService {
	
	@Autowired
	private UpmsDepartmentMapper mapper ;
	
	@Autowired
	private UpmsUserCompanyDeptAssignMapper upmsUserCompanyDeptAssignMapper;
	
	@Override
	public List<UpmsDepartment> selectRoot(UpmsDepartment entity) {
		return this.mapper.selectRoot(entity);
	}
	
	@Override
	public int delete(Integer id) throws BizException {
		return recursiveDelete(id);
	}
	
	private int recursiveDelete(Integer id) {
		List<UpmsDepartment> loadChildrenNode = this.selectChildren(id) ;
		if(null != loadChildrenNode) {
			for (UpmsDepartment department : loadChildrenNode) {
				recursiveDelete(department.getId());
			}
		}
		
		//删除该部门下的用户的关联关系
		Condition condition = new Condition(UpmsUserCompanyDeptAssign.class) ;
		condition.createCriteria().andEqualTo("departmentId", id);
		this.upmsUserCompanyDeptAssignMapper.deleteByCondition(condition) ;
		
		return super.delete(id) ;
	}

	@Override
	public List<UpmsDepartment> selectChildren(Integer pid) {
		return this.mapper.selectChildren(pid);
	}

	@Override
	public List<UpmsDepartment> tree(UpmsDepartment entity) {
		List<UpmsDepartment> list = new ArrayList<UpmsDepartment>() ;
		
		List<UpmsDepartment> selectRoot = this.selectRoot(entity) ;
		for (UpmsDepartment department : selectRoot) {
			list.add(recursive(department)) ;
		}
		return list;
	}
	
	private UpmsDepartment recursive(UpmsDepartment entity) {
		List<UpmsDepartment> selectChildren = this.selectChildren(entity.getId()) ;
		if(null != selectChildren && !selectChildren.isEmpty()) {
			List<UpmsDepartment> children = new ArrayList<UpmsDepartment>() ;
			
			for (UpmsDepartment child : selectChildren) {
				children.add(recursive(child)) ;
			}
			
			entity.setChildren(children);
		}
		return entity ;
	}

	@Override
	public void removeDepartmentAssignUser(String ids) {
		this.upmsUserCompanyDeptAssignMapper.deleteByIds(ids) ;
		
	}
	
}
